<?php

namespace app\admin\controller\communityapply;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;

/**
 * 社区课程预约报名管理
 *
 * @icon fa fa-calendar-check-o
 */
class Communityapply extends Backend
{

    /**
     * Apply模型对象
     */
    protected $model = null;
    protected $noNeedRight = ['getBookingDetails', 'searchUsers', 'searchCourses'];
    protected $noNeedLogin = ['getBookingDetails', 'searchUsers', 'searchCourses'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Apply');
        $this->view->assign("statusList", $this->model->getStatusList());
        //        $this->view->assign("tableTypeList", $this->model->getTableTypeList());
        //        $this->view->assign("applyTypeList", $this->model->getApplyTypeList());
        //        $this->view->assign("courseTypeList", $this->model->getCourseTypeList());
        //        $this->view->assign("isRealList", $this->model->getIsRealList());
        //        $this->view->assign("isCloseList", $this->model->getIsCloseList());
        //        $this->view->assign("isOpenedList", $this->model->getIsOpenedList());
        //        $this->view->assign("isFinishedList", $this->model->getIsFinishedList());
        //        $this->view->assign("isUserEndList", $this->model->getIsUserEndList());
        //        $this->view->assign("isEndList", $this->model->getIsEndList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        $user = $this->auth->getUserInfo();
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 只显示社区课程报名 (table_type=2)
            //$where['table_type'] = 2;

            // 添加城市和学校过滤逻辑
            $cityId = $this->request->get('city_id');
            $schoolId = $this->request->get('school_id');

            // 创建额外的查询条件数组
            $extraWhere = [];

            // 根据用户组进行数据过滤
            if ($user && isset($user['group_id'])) {
                if ($user['group_id'] == 3) { // 学校管理用户
                    if (isset($user['school_id']) && !empty($user['school_id'])) {
                        $extraWhere[] = ['school_id', 'like', '%' . $user['school_id'] . '%'];
                    }
                } elseif ($user['group_id'] == 8) { // 社区管理用户
                    if (isset($user['city_id']) && !empty($user['city_id'])) {
                        $extraWhere[] = ['city_id', 'like', '%' . $user['city_id'] . '%'];
                    }
                }
            }

            // 前端筛选条件
            if (!empty($cityId)) {
                $extraWhere[] = ['city_id', 'like', '%' . $cityId . '%'];
            }
            if (!empty($schoolId)) {
                $extraWhere[] = ['school_id', 'like', '%' . $schoolId . '%'];
            }

            $query = $this->model->where($where);

            // 添加额外的查询条件
            foreach ($extraWhere as $condition) {
                $query->where($condition[0], $condition[1], $condition[2]);
            }
            $query->where('status', 1);
            $total = $query->order("weigh desc")->order($sort, $order)->count();

            $list = $this->model->where($where)->where('status', 1);

            // 添加额外的查询条件
            foreach ($extraWhere as $condition) {
                $list->where($condition[0], $condition[1], $condition[2]);
            }

            $list = $list->order("weigh desc");

            // 只有当排序字段不是 weigh 时，才添加额外的排序
            if ($sort != 'weigh') {
                $list = $list->order($sort, $order);
            }

            $list = $list->limit($offset, $limit)->select();

            $list = collection($list)->toArray();
            for ($i = 0; $i < count($list); $i++) {
                $list[$i]['city_id'] = model('Cityarea')->getCity_idTextAttr($list[$i]['city_id'], $list[$i]);
                $list[$i]['school_id'] = model('School')->getSchool_idTextAttr($list[$i]['school_id'], $list[$i]);
                //$list[$i]['table_type_text'] = $this->model->getTableTypeTextAttr($list[$i]['table_type'], $list[$i]);
                //                $list[$i]['status_text'] = $this->model->getStatusTextAttr($list[$i]['status'], $list[$i]);
                //                $list[$i]['apply_type_text'] = $this->model->getApplyTypeTextAttr($list[$i]['apply_type'], $list[$i]);
                //                $list[$i]['course_type_text'] = $this->model->getCourseTypeTextAttr($list[$i]['course_type'], $list[$i]);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }

                    $user = $this->auth->getUserInfo();
                    unset($params['id']);

                    // 设置默认值
                    $params['status'] = isset($params['status']) ? $params['status'] : 1;
                    $params['table_type'] = 2; // 固定为社区课程
                    $params['userid'] = $user['id'];

                    // 自动插入session中的城市和学校ID
                    if (isset($user['city_id']) && !empty($user['city_id'])) {
                        $params['city_id'] = $user['city_id'];
                    }
                    if (isset($user['school_id']) && !empty($user['school_id'])) {
                        $params['school_id'] = $user['school_id'];
                    }

                    // 处理时间字段 - 转换为标准日期时间格式
                    if (isset($params['start_time']) && !empty($params['start_time'])) {
                        $params['start_time'] = date('Y-m-d H:i:s', strtotime($params['start_time']));
                    }
                    if (isset($params['end_time']) && !empty($params['end_time'])) {
                        $params['end_time'] = date('Y-m-d H:i:s', strtotime($params['end_time']));
                    }
                    if (isset($params['dead_time']) && !empty($params['dead_time'])) {
                        $params['dead_time'] = date('Y-m-d H:i:s', strtotime($params['dead_time']));
                    }

                    // 移除手动设置的时间字段，让模型自动处理
                    unset($params['update_time'], $params['create_time']);

                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success('添加成功', null, ['refresh' => true]);
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        // 设置管理员配置信息到前端
        $user = $this->auth->getUserInfo();
        $this->assignconfig("admin", [
            'id' => $user['id'],
            'username' => $user['username'],
            'city_id' => $user['city_id'] ?? '',
            'school_id' => $user['school_id'] ?? '',
            'rel_type' => $user['rel_type'] ?? '',
            'rel_id' => $user['rel_id'] ?? '',
            'group_id' => $user['group_id'] ?? ''
        ]);

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }

                    // 确保table_type始终为2
                    $params['table_type'] = 2;

                    // 处理时间字段 - 转换为标准日期时间格式
                    if (isset($params['start_time']) && !empty($params['start_time'])) {
                        $params['start_time'] = date('Y-m-d H:i:s', strtotime($params['start_time']));
                    }
                    if (isset($params['end_time']) && !empty($params['end_time'])) {
                        $params['end_time'] = date('Y-m-d H:i:s', strtotime($params['end_time']));
                    }
                    if (isset($params['dead_time']) && !empty($params['dead_time'])) {
                        $params['dead_time'] = date('Y-m-d H:i:s', strtotime($params['dead_time']));
                    }

                    // 移除手动设置的时间字段，让模型自动处理
                    unset($params['update_time'], $params['create_time']);

                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success('编辑成功', null, ['refresh' => true]);
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        // 设置管理员配置信息到前端
        $user = $this->auth->getUserInfo();
        $this->assignconfig("admin", [
            'id' => $user['id'],
            'username' => $user['username'],
            'city_id' => $user['city_id'] ?? '',
            'school_id' => $user['school_id'] ?? '',
            'rel_type' => $user['rel_type'] ?? '',
            'rel_id' => $user['rel_id'] ?? '',
            'group_id' => $user['group_id'] ?? ''
        ]);

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 获取预约详情数据
     */
    public function getBookingDetails()
    {
        // 记录调试日志
        $logFile = $_SERVER["DOCUMENT_ROOT"] . "/../runtime/log/booking_debug.log";

        $form_id = $this->request->get('form_id', 0);
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $offset = $this->request->get('offset', 0);

        // 调试日志
        file_put_contents($logFile, date('Y-m-d H:i:s') . " - 接收参数: form_id={$form_id}, page={$page}, limit={$limit}, offset={$offset}\n", FILE_APPEND);

        if (!$form_id) {
            file_put_contents($logFile, date('Y-m-d H:i:s') . " - 错误: 项目ID为空\n", FILE_APPEND);
            return json(['code' => 0, 'msg' => '项目ID不能为空']);
        }

        try {
            // 查询预约详情数据，关联用户表和班级表
            $query = Db::name('eb_apply_form_item')
                ->alias('item')
                ->join('user u', 'item.user_id = u.id', 'LEFT')
                ->join('fa_ocation_class c', 'item.classes_id = c.id', 'LEFT')
                ->where('item.form_id', $form_id)  // 启用form_id过滤
                ->where('item.delete_time', null)
                ->field([
                    'item.id',
                    'item.form_id',
                    'item.user_id',
                    'u.nickname as user_name',
                    'u.gender as user_gender',
                    'u.mobile as user_mobile',
                    'c.name as class_name',
                    'item.create_time',
                    'item.status',
                    'item.classes_type',
                    'item.classes_id'
                ]);

            // 调试SQL语句
            $sql = $query->buildSql();
            file_put_contents($logFile, date('Y-m-d H:i:s') . " - SQL语句: {$sql}\n", FILE_APPEND);

            // 获取总数
            $total = (clone $query)->count();
            file_put_contents($logFile, date('Y-m-d H:i:s') . " - 查询总数: {$total}\n", FILE_APPEND);

            // 分页查询
            if ($offset > 0) {
                $page = intval($offset / $limit) + 1;
            }

            $list = $query->page($page, $limit)
                ->select();

            file_put_contents($logFile, date('Y-m-d H:i:s') . " - 查询结果数量: " . count($list) . "\n", FILE_APPEND);
            file_put_contents($logFile, date('Y-m-d H:i:s') . " - 原始数据: " . json_encode($list) . "\n", FILE_APPEND);

            // 处理数据
            foreach ($list as &$item) {
                // 格式化性别
                //$item['user_gender'] = $item['user_gender'] == 1 ? '男' : ($item['user_gender'] == 2 ? '女' : '未知');

                // 格式化状态
                $item['status_text'] = $item['status'] == 1 ? '正常' : '禁用';

                // 格式化创建时间 - 转换为时间戳供前端使用
                if ($item['create_time']) {
                    $item['create_time'] = strtotime($item['create_time']);
                }

                // 如果没有班级名称，显示默认文本
                if (empty($item['class_name'])) {
                    $item['class_name'] = '未指定班级';
                }
            }

            $result = [
                'total' => $total,
                'rows' => $list
            ];

            file_put_contents($logFile, date('Y-m-d H:i:s') . " - 最终返回数据: " . json_encode($result) . "\n", FILE_APPEND);

            return json($result);
        } catch (\Exception $e) {
            $errorMsg = '获取预约详情失败: ' . $e->getMessage();
            file_put_contents($logFile, date('Y-m-d H:i:s') . " - 异常: {$errorMsg}\n", FILE_APPEND);
            return json(['code' => 0, 'msg' => $errorMsg]);
        }
    }

    /**
     * 更新预约申请状态
     */
    public function updateBookingStatus()
    {
        if (!$this->request->isPost()) {
            $this->error('请求方式错误');
        }

        $id = $this->request->post('id');
        $status = $this->request->post('status');

        if (empty($id) || !in_array($status, [0, 1, 2])) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }

        try {
            $result = Db::name('eb_apply_form_item')
                ->where('id', $id)
                ->update([
                    'status' => $status,
                    'update_time' => time()
                ]);

            if ($result) {
                return json(['code' => 1, 'msg' => '状态更新成功']);
            } else {
                return json(['code' => 0, 'msg' => '状态更新失败']);
            }
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '更新失败: ' . $e->getMessage()]);
        }
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
            } catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success('删除成功', null, ['refresh' => true]);
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 批量更新
     */
    public function multi($ids = "")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            try {
                foreach ($list as $index => $item) {
                    $count += $item->delete();
                }
            } catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success('操作成功', null, ['refresh' => true]);
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
